package org.pro.View;

import org.pro.Net.Client;
import org.pro.Net.Server;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

public class GameInit extends JFrame {
    private JTextField ipTextField;
    private JTextField portTextField;
    private JLabel ipLabel;
    private JLabel portLabel;
    private Server server;
    private Client client;
    private boolean isGameStarted = false;

    public GameInit() {
        // 设置窗口标题
        setTitle("游戏选择界面咯！");

        // 设置窗口大小
        setSize(300, 250);

        // 设置窗口关闭操作
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 创建面板
        JPanel panel = new JPanel();
        panel.setLayout(null); // 设置空布局

        // 创建标签
        ipLabel = new JLabel("IP 地址:");
        portLabel = new JLabel("端口:");

        // 创建输入框并设置默认值
        ipTextField = new JTextField("localhost"); // 默认值设置为 localhost
        portTextField = new JTextField("12345");   // 默认值设置为 12345

        // 创建按钮
        JButton serverButton = new JButton("创建服务器");
        JButton clientButton = new JButton("连接服务器");

        // 设置组件的大小和位置
        ipLabel.setBounds(30, 30, 80, 25);
        ipTextField.setBounds(120, 30, 150, 25);
        portLabel.setBounds(30, 70, 80, 25);
        portTextField.setBounds(120, 70, 150, 25);
        serverButton.setBounds(30, 160, 120, 30);
        clientButton.setBounds(160, 160, 120, 30);

        // 添加按钮事件监听器
        serverButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int port = Integer.parseInt(portTextField.getText());
                try {
                    server = new Server(12345);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
                server.start();
                server.run();
            }
        }); // 这里需要闭合括号


        clientButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String ip = ipTextField.getText();
                int port = Integer.parseInt(portTextField.getText());
                client = new Client();
                if (client.contect(ip, port)) {
                    System.out.println("玩家:"+client.id+"已连接");
                    client.run();
                } else {
                    JOptionPane.showMessageDialog(null, "连接失败！");
                }
            }
        });

        // 将组件添加到面板
        panel.add(ipLabel);
        panel.add(ipTextField);
        panel.add(portLabel);
        panel.add(portTextField);
        panel.add(serverButton);
        panel.add(clientButton);

        // 将面板添加到窗口
        add(panel);

        // 设置窗口可见
        setVisible(true);
    }
}
